<?php
include_once 'opds.php';

$stats = array();
$stats['langs'] = 0;
$stats['books'] = 0;
$stats['genres'] = 0;
$stats['authors'] = 0;

$opds->open_index();
$opds->idx->exec("PRAGMA synchronous=0");
$opds->index_create_structure();

$opds->index_begin();
$opds->scan_inpx(function ($af, $archname) {
	global $opds, $stats;

	$lang = $opds->index_get_lang($af[11]);
	if ($lang)
		$lang_id = $lang['id'];
	else {
		$lang_id = $opds->index_add_lang($af[11]);
		$stats['langs']++;
	}
	$book = array();
	$book['title'] = $af[2];
	$book['archive'] = $archname;
	$book['file'] = $af[5];
	$book['ext'] = $af[9];
	$book['size'] = $af[6];
	$book['lang'] = $lang_id;
	$book['date'] = strtotime($af[10]);
	$book['librate'] = $af[12];
	$book_id = $opds->index_add_book($book);
	$stats['books']++;

	$agenres = explode(":", $af[1]);
	foreach ($agenres as $genre) {
		if (empty($genre))
			continue;
		$rgenre = $opds->index_get_genre($genre);
		if ($rgenre)
			$genre_id = $rgenre['id'];
		else {
			$genre_id = $opds->index_add_genre($genre);
			$stats['genres']++;
		}
		$opds->index_add_book_genre($book_id, $genre_id);
	}

	$aauthors = explode(":", $af[0]);
	foreach ($aauthors as $author) {
		$author = mb_strtoupper($author);
		if (empty($author))
			continue;
		$aauthor = explode(",", $author, 3);
		$aauthor2 = isset($aauthor[2]) ? $aauthor[2] : '';
		$rauthor = $opds->index_get_author($aauthor[0], $aauthor[1], $aauthor2);
		if ($rauthor)
			$author_id = $rauthor['id'];
		else {
			$author_id = $opds->index_add_author($aauthor[0], $aauthor[1], $aauthor2);
			$stats['authors']++;
		}
		$opds->index_add_book_author($book_id, $author_id);
	}
	if ($stats['books'] % 5000 === 0) {
		$opds->index_commit();
		$opds->index_begin();
	}

	if ($stats['books'] % 100 === 0)
		echo "\x0dBooks: " . $stats['books'] . "; langs: " . $stats['langs'] . "; genres: " . $stats['genres'] . "; authors: " . $stats['authors'];
});
$opds->index_commit();

echo "\n\nCreating indices...";
$opds->index_create_indices();
$opds->idx->exec("PRAGMA synchronous=2");
echo "done\n";
